package com.example.emailcraft.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.emailcraft.entity.Roles;
import com.example.emailcraft.mapper.RolesMapper;
import com.example.emailcraft.mapper.UserRolesMapper;
import com.example.emailcraft.service.IRolesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author scj
 * @since 2025-01-21
 */
@Service
public class RolesServiceImpl extends ServiceImpl<RolesMapper, Roles> implements IRolesService {

    @Autowired
    private RolesMapper roleMapper;

    @Autowired
    private UserRolesMapper userRoleMapper;

    /**
     * 为用户分配默认角色（如 USER）
     */
    @Transactional
    @Override
    public void assignDefaultRoleToUser(Integer userId) {
        // 1. 查询默认角色（如 USER）
        String defaultRoleCode = "user";
        Integer roleId = roleMapper.findIdByRoleCode(defaultRoleCode);

        if (roleId == null) {
            throw new RuntimeException("默认角色不存在");
        }

        // 2. 分配角色
        userRoleMapper.insert(userId, roleId);
    }
}
